package com.suyu.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.suyu.annotation.AuthCheck;
import com.suyu.common.BaseResponse;
import com.suyu.common.ErrorCode;
import com.suyu.common.ResultUtils;
import com.suyu.constant.UserConstant;
import com.suyu.exception.BusinessException;
import com.suyu.exception.ThrowUtils;
import com.suyu.model.dto.user.*;
import com.suyu.model.entity.User;
import com.suyu.model.vo.LoginUserVO;
import com.suyu.service.UserService;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author tmh
 * @date 2023/9/13 14:10
 * @description
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

/*    @Resource
    private RedisTemplate<String, String> redisTemplate;*/

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public BaseResponse userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {

        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        BaseResponse baseResponse = userService.userRegister(userAccount, userPassword, checkPassword);
        System.out.println(baseResponse.getClass());
        return baseResponse;
    }


    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
//        String captcha = userLoginRequest.getCaptcha();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return userService.userLogin(userAccount, userPassword/*,captcha*/, request);
    }

    /**
     * 用户退出登录状态
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation("用户退出登录")
    public BaseResponse userLogout(HttpServletRequest request) {
        return userService.userLogout(request);
    }

    /**
     * 获取当前已经登录的用户
     *
     * @param request
     * @return
     */
    @ApiOperation("获取当前登录用户")
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVo(user));
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("删除用户")
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     *
     * @param userUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("管理员更新用户信息")
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return ResultUtils.success(true);
    }

    /**
     * 更新个人信息
     *
     * @param userUpdateMyRequest
     * @param request
     * @return
     */
    @PostMapping("/update/my")
    @ApiOperation("更新用户个人信息")
    public BaseResponse<Boolean> updateMyUser(@RequestBody UserUpdateMyRequest userUpdateMyRequest,
                                              HttpServletRequest request) {
        if (userUpdateMyRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        User user = new User();
        BeanUtils.copyProperties(userUpdateMyRequest, user);
        user.setId(loginUser.getId());
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 获取用户列表
     *
     * @param userPageRequest
     * @return
     */
    @PostMapping("/user/list")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("获取用户列表")
    public BaseResponse<Page<User>> listUserVObyPage(@RequestBody UserPageRequest userPageRequest) {
        int size = userPageRequest.getSize();
        int currentPage = userPageRequest.getCurrentPage();
        Page<User> page = userService.page(new Page<>(currentPage, size));
        return ResultUtils.success(page);
    }

    /* 获取验证码图片*/
/*
    @GetMapping("/getVerifyCode")
    @ApiOperation("获取验证码")
    public void getVerificationCode(HttpServletResponse response, HttpServletRequest request) throws IOException {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();

        //生成一个uuid，对应一个验证码
        String uuid = RandomUtil.randomNumbers(10);
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        lineCaptcha.write(response.getOutputStream());
        //把uuid放在session里面
        request.getSession().setAttribute("uuid", uuid);

        //把uuid和验证码存入到redis里面
        ops.set(uuid, lineCaptcha.getCode());
        //设置验证码的过期时间为2min
        redisTemplate.expire(uuid, 2, TimeUnit.MINUTES);
        System.out.println(redisTemplate.opsForValue().get(uuid));
        log.info("uuid的值为{},时间:{}：获取验证码,值为{}", uuid, new Date().toString(), lineCaptcha.getCode());
    }
*/


}
